// 生成无限分类树
var tree = function(categoryJSON, pid) {
  var rtn = []
  for (var i in categoryJSON) {
    if ((categoryJSON[i].pid === pid)) {
      var children = tree(categoryJSON, categoryJSON[i]._id)
      if (children.length > 0) {
        categoryJSON[i].children = children
      }
      rtn.push(categoryJSON[i])
    }
  }
  return rtn
}

// 生成父节点单线路径
var findAncestors = function(arr, _id) {
  for (var i in arr) {
    if (arr[i]._id === _id) {
      // 顶级分类为空，意味着是父类
      if (arr[i].pid !== '') {
        return [_id].concat(findAncestors(arr, arr[i].pid))
      } else {
        // 否则返回自身
        return [_id]
      }
    }
  }
}

// 判断上传类型与大小
var uploadLimit = function(file, cb) {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const mb = 0.5
  const isLt = file.size / 1024 / 1024 < mb
  if (!isJPG) {
    cb('上传图片只能是jpg/png格式!')
    return false
  }
  if (!isLt) {
    cb('上传图片大小不能超过' + mb * 1000 + 'kb!')
    return false
  }
  return true
}

module.exports = { tree, findAncestors, uploadLimit }
